# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import copy
import json
import uuid
from collections import OrderedDict

from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from future.builtins import str
from wenlincms.utils.views import render

from mainsys.settings import neo4jhost_host
from wlapps.utils.base62 import wlencode, wldecode
from wlapps.utils.common import kongtostr
from wlmodels.codes.dicts import cb18_dict
from wlmodels.codes.dicts import ex02_dict
from wlmodels.codes.models import ELNic, ELRegion
from wlmodels.company.models import ELPost, ELClass, ELManager, ELInv, ELPerson, ELGeti, ELBasic
from wlmodels.companyplus.models import ELFinanceTax
from wlviews.apis.neo4japi import Neo4jAPI
from wlviews.report.tupu import road_id_from_dict, road_name_from_id, gen_touzi_edgetext, road_edge_distinct
from wlviews.saas.fee import customer_verify_fee, noauth_redirct_iframe, noauth_redirct_url
from wlviews.saas.utils import related_road_json


@csrf_exempt
@never_cache
@login_required
def related_single(request):
    if customer_verify_fee(request, saas_pindao="20"):
        return HttpResponseRedirect(noauth_redirct_url)

    method = request.GET.get("method")
    if not method:
        return render(request, "saas/related/related_single.html", {})

    elif method == "loadnode":
        entid = request.POST['entid'] if 'entid' in request.POST else ''
        result = []
        if not entid:
            obj_result = ELPost.objects.filter(entid__in=[11588539, 6384641, 10952139, 8363945])
            for obj in obj_result:
                result.append({"entid": obj.entid, "ENTNAME": obj.ENTNAME, "parent": "", "isLeaf": False, "expanded": False})
        else:
            childs = ELRegion.objects.filter(entid1=entid).order_by("-FUNDEDRATIO").values_list("entid2", flat=True)
            childs = list(set(childs))
            obj_result = ELPost.objects.filter(entid__in=childs)
            for obj in obj_result:
                result.append({"entid": obj.entid, "ENTNAME": obj.ENTNAME, "parent": entid,
                               "isLeaf": False, "expanded": False})
        # 查看每个节点是否叶子节点
        for obj in result:
            child = ELRegion.objects.filter(entid1=obj['entid'])
            if len(child):
                obj['isLeaf'] = False
                obj['expanded'] = False
            else:
                obj['isLeaf'] = True
        return HttpResponse(json.dumps(result))

    elif method == "loadtable":
        entid = request.POST['entid'] if 'entid' in request.POST else ''
        result = {"total": 0, "data": []}
        # 进行计费
        if customer_verify_fee(request, saas_pindao="20", saas_item="30", tkey="e" + str(entid)):
            return HttpResponse(json.dumps(result))
        pageindex = int(request.POST['pageIndex']) if 'pageIndex' in request.POST else 0
        pagesize = int(request.POST['pageSize']) if 'pageSize' in request.POST else 20
        sortfield = request.POST['sortField'] if 'sortField' in request.POST else ''
        sortorder = '-' if 'sortOrder' in request.POST and request.POST['sortOrder'] == 'desc' else ''
        if entid:
            # 添加当前企业
            if not pageindex:
                the_coms = ELPost.objects.filter(entid=entid)
                if len(the_coms):
                    the_tax = ELFinanceTax.objects.filter(entid_id=entid).order_by("-year")
                    the_revenue = the_tax[0].revenue if len(the_tax) else ""
                    the_total_profit = the_tax[0].total_profit if len(the_tax) else ""
                    result["data"].append({"entid": entid, "ENTNAME": the_coms[0].ENTNAME + "（当前企业）", "relation": "", "SUBCONAM": "",
                                           "CURRENCY": "", "FUNDEDRATIO": "", "CONDATE": "", "name": "", "POSITION_A": "",
                                           "POSITION_B": "", "gender": "", "nativeplace": "", "birth": "",
                                           "legalperson_name": the_coms[0].c_basic.legalperson_name,
                                           "opendate": the_coms[0].c_basic.opendate.strftime('%Y-%m-%d') if the_coms[0].c_basic.opendate else "",
                                           "staffnum": the_coms[0].c_basic.staffnum,
                                           "eststatus": the_coms[0].c_basic.eststatus, "regadd": the_coms[0].c_basic.regadd,
                                           "nic": the_coms[0].c_class.nic_id.fulltitle if the_coms[0].c_class.nic_id else "",
                                           "region": the_coms[0].c_class.region_id.fulltitle if the_coms[0].c_class.region_id else "",
                                           "regcapital_amount": the_coms[0].c_basic.regcapital_amount,
                                           "revenue": the_revenue, "total_profit": the_total_profit})

            # 添加下级企业
            search_fields = {"entid1": entid}
            # 添加筛选
            flag = 'sfield' in request.POST
            sfield = request.POST['sfield'].split("￥") if flag else []
            svalue = request.POST['svalue'].split("￥") if flag else []
            svalue = [x.strip() for x in svalue] if flag else []
            if len(sfield) and len(sfield) == len(svalue):
                entid2_in_list, childs = None, []
                if "region_id" in sfield or "nic_id" in sfield or "revenue__gte" in sfield or "revenue__lte" in sfield \
                        or "total_profit__gte" in sfield or "total_profit__lte" in sfield:
                    childs = list(ELRegion.objects.filter(entid1=entid).values_list("entid2", flat=True))
                tax_lookups = {"entid_id__in": childs, "islatest": True}
                for i in xrange(len(sfield)):
                    if len(svalue[i]):
                        if sfield[i] == "region_id":
                            ids = ELRegion.objects.filter(id=svalue[i])
                            if len(ids):
                                new_ids = list(ELClass.objects.filter(entid__in=childs, region_id_id__in=ids[0].allsiblings.split(','))
                                               .values_list("entid", flat=True))
                                entid2_in_list = list(set(entid2_in_list) & set(new_ids)) if entid2_in_list is not None else new_ids
                        elif sfield[i] == "nic_id":
                            ids = ELNic.objects.filter(id=svalue[i])
                            if len(ids):
                                new_ids = list(ELClass.objects.filter(entid__in=childs, nic_id_id__in=ids[0].allsiblings.split(','))
                                               .values_list("entid", flat=True))
                                entid2_in_list = list(set(entid2_in_list) & set(new_ids)) if entid2_in_list is not None else new_ids
                        elif sfield[i] in ["total_profit__gte", "total_profit__lte", "revenue__gte", "revenue__lte"]:
                            tax_lookups[sfield[i]] = svalue[i]
                        else:
                            search_fields[sfield[i]] = svalue[i]
                if len(tax_lookups.keys()) > 2:
                    new_ids = list(ELFinanceTax.objects.filter(**tax_lookups).values_list("entid_id", flat=True))
                    entid2_in_list = list(set(entid2_in_list) & set(new_ids)) if entid2_in_list is not None else new_ids
                if entid2_in_list is not None:
                    search_fields["entid2__in"] = entid2_in_list
            obj_result = ELRegion.objects.filter(**search_fields)

            # 添加排序
            if sortfield in ["entid"]:
                obj_result = obj_result.order_by(sortorder + "entid2")
            elif sortfield == "SUBCONAM":
                obj_result = obj_result.exclude(SUBCONAM__isnull=True).order_by(sortorder + sortfield)
            elif sortfield == "FUNDEDRATIO":
                obj_result = obj_result.exclude(FUNDEDRATIO__isnull=True).order_by(sortorder + sortfield)
            elif sortfield == "name":
                obj_result = obj_result.exclude(name__isnull=True).exclude(name="").order_by(sortorder + sortfield)
            elif sortfield in ["regcapital_amount", "staffnum"]:
                obj_result = obj_result.order_by(sortorder + "entid2__c_basic__" + sortfield)
            childs = obj_result.values_list("entid2", flat=True)
            childs = list(set(childs))
            result["total"] = len(childs) + 1
            obj_result = obj_result[pageindex * pagesize:pageindex * pagesize + pagesize]

            # 添加下级企业的数据
            obj_processed = []  # 用于去重
            for obj in obj_result:
                if obj.entid2 in obj_processed:
                    continue
                obj_processed.append(obj.entid2)
                obj = obj.entid2
                the_relations = ELRegion.objects.filter(entid1=entid, entid2=obj.entid)
                the_relation2, the_relation3 = "", ""
                if len(the_relations) == 1:
                    the_relation = "投资" if the_relations[0].relation[0] == "2" else "任职"
                    the_relation2 = the_relations[0]
                    the_relation3 = the_relations[0]
                else:
                    the_relation = "投资并任职"
                    for the_r in the_relations:
                        if the_r.SUBCONAM or the_r.FUNDEDRATIO:
                            the_relation2 = the_r
                        elif the_r.POSITION_A or the_r.POSITION_B:
                            the_relation3 = the_r
                the_tax = ELFinanceTax.objects.filter(entid_id=obj.entid).order_by("-year")
                the_revenue = the_tax[0].revenue if len(the_tax) else ""
                the_total_profit = the_tax[0].total_profit if len(the_tax) else ""
                result["data"].append({"entid": obj.entid, "ENTNAME": obj.ENTNAME, "relation": the_relation,
                                       "SUBCONAM": the_relation2.SUBCONAM if the_relation2 else "",
                                       "CURRENCY": the_relation2.CURRENCY if the_relation2 else "",
                                       "FUNDEDRATIO": str(the_relation2.FUNDEDRATIO * 100) + "%" if the_relation2 and
                                                                                                    the_relation2.FUNDEDRATIO else "",
                                       "CONDATE": the_relation2.CONDATE.strftime('%Y-%m-%d') if the_relation2 and the_relation2.CONDATE else "",
                                       "name": the_relation3.name if the_relation3 else (the_relation2.name if the_relation2 else ""),
                                       "POSITION_A": the_relation3.POSITION_A if the_relation3 else "",
                                       "POSITION_B": the_relation3.POSITION_A if the_relation3 else "",
                                       "gender": the_relation3.get_gender_display() if the_relation3 else "",
                                       "nativeplace": the_relation3.nativeplace if the_relation3 else "",
                                       "birthyear": the_relation3.birthyear if the_relation3 else "",
                                       "legalperson_name": obj.c_basic.legalperson_name,
                                       "opendate": obj.c_basic.opendate.strftime('%Y-%m-%d') if obj.c_basic.opendate else "",
                                       "staffnum": obj.c_basic.staffnum,
                                       "eststatus": obj.c_basic.eststatus, "regadd": obj.c_basic.regadd,
                                       "nic": obj.c_class.nic_id.fulltitle if obj.c_class.nic_id else "",
                                       "region": obj.c_class.region_id.fulltitle if obj.c_class.region_id else "",
                                       "regcapital_amount": obj.c_basic.regcapital_amount,
                                       "revenue": the_revenue, "total_profit": the_total_profit})
        return HttpResponse(json.dumps(result))


# 单点关联的html模块
@never_cache
@login_required
def single_json(request):
    ntype = request.GET.get('ntype')
    pk = request.GET.get('pk')
    direction = request.GET.get('relationdirection')
    filter_data = {
        'region_id_start': request.GET.get('region_id'),
        'nic_id__start': request.GET.get('nic_id'),
        'ENTSTATUS': request.GET.get('ENTSTATUS'),
        'REGCAP__gte': request.GET.get('REGCAP1'),
        'REGCAP__lte': request.GET.get('REGCAP2'),
        'ESDATE__gte': request.GET.get('ESDATE1'),
        'ESDATE__lte': request.GET.get('ESDATE2')
    }
    result = {}
    if pk and ntype:
        # 取得公司关联对象
        def get_com_relation(companyid):
            # 1向下 投资任职 2 向下投资 3  向下任职 4 向上股东
            obj_list = []
            if direction == '1':
                pass
            elif direction == '2':
                obj_list = ELInv.objects.filter(entid_inv=companyid).values_list("entobj", flat=True)
            elif direction == '3':
                pass
            elif direction == '4':
                obj_list = ELInv.objects.filter(entobj=companyid).values_list("entobj", flat=True)
            return obj_list

        # 取得个人关联对象
        def get_per_relation(personid):
            # 1向下 投资任职 2 向下投资 3  向下任职 4 向上股东
            obj_list = []
            if direction == '1':
                obj_l1 = set(ELInv.objects.filter(personid=personid).values("entobj",))
                obj_l2 = set(ELManager.objects.filter(personid=personid).values_list("entobj", flat=True))
                obj_list = list(obj_l1 & obj_l2)
            elif direction == '2':
                obj_list = ELInv.objects.filter(personid=personid).values_list("entobj", flat=True)
            elif direction == '3':
                obj_list = ELManager.objects.filter(personid=personid).values_list("entobj", flat=True)
            elif direction == '4':
                pass
            return obj_list

        result_list = []
        if ntype in ['1', '2']:
            result_list = get_com_relation(pk)
        elif ntype in ['3', '4']:
            result_list = get_per_relation(pk)
        if result_list:
            pass
            # obj_result = ELPost.objects.filter(entid__in=result_list)
            # for obj in obj_result:
            #     tnew_child = {"id": str(uuid.uuid4()), "eid": "e" + str(obj.id), "name": obj.ENTNAME,
            #                   "tags": "1",
            #                   "size": "5", "relation": "投资(%s%%)" % pinv.CONPROP}
            #     result["children"].append(tnew_child)

    # 进行计费
    # if customer_verify_fee(request, saas_pindao="20", saas_item="40", tkey="%s-%s-%s-%s-%s" % (ntype1, ntype2, pk1, pk2, depth)):
    #     return HttpResponseRedirect(noauth_redirct_iframe)
    return HttpResponse(json.dumps(result))


# 单点关联的html模块
@never_cache
@login_required
def company_single(request):
    data = {
        'ntype': request.GET.get('ntype'),
        'pk': request.GET.get('pk'),
        'relationdirection': request.GET.get('relationdirection'),
        'region_id': request.GET.get('region_id'),
        'nic_id': request.GET.get('nic_id'),
        'ENTSTATUS': request.GET.get('ENTSTATUS'),
        'REGCAP1': request.GET.get('REGCAP1'),
        'REGCAP2': request.GET.get('REGCAP2'),
        'ESDATE1': request.GET.get('ESDATE1'),
        'ESDATE2': request.GET.get('ESDATE2')
    }
    # 进行计费
    # if customer_verify_fee(request, saas_pindao="20", saas_item="40", tkey="%s-%s-%s-%s-%s" % (ntype1, ntype2, pk1, pk2, depth)):
    #     return HttpResponseRedirect(noauth_redirct_iframe)
    return render(request, "saas/related/single.html", {'data': json.dumps(data)})


@csrf_exempt
@never_cache
@login_required
def related_multi(request):
    method = request.GET.get("method")
    if not method:
        return render(request, "saas/related/related_multi.html", {})


# 企业图谱json数据生成主函数，d3所需
def get_tupu_json(request, entid):
    # 个体对外投资和任职的函数
    def get_person_child(tentid, tpersonid, tresult, tnodes_exist):
        t_invs = ELInv.objects.filter(personid=tpersonid).exclude(entobj=tentid)
        if len(t_invs):
            for pinv in t_invs:
                if "e" + str(pinv.entobj_id) not in tnodes_exist:
                    tnew_child = {"id": str(uuid.uuid4()), "eid": "e" + str(pinv.entobj_id), "name": pinv.entid.ENTNAME,
                                  "tags": "1",
                                  "size": "5", "relation": "投资(%s%%)" % pinv.CONPROP}
                    tresult["children"].append(tnew_child)
                    tnodes_exist.append("e" + str(pinv.entobj_id))
        t_positions = ELManager.objects.filter(personid=tpersonid).exclude(entobj=tentid)
        if len(t_positions):
            for tposition in t_positions:
                if "e" + str(tposition.entobj_id) not in tnodes_exist:
                    tnew_child = {"id": str(uuid.uuid4()), "eid": "e" + str(tposition.entobj_id),
                                  "name": tposition.entid.ENTNAME, "tags": "1",
                                  "size": "5", "relation": tposition.get_POSITION_display()}
                    tresult["children"].append(tnew_child)
                    tnodes_exist.append("e" + str(tposition.entobj_id))
        return tresult, tnodes_exist

    result = {"children": []}
    isajax = request.GET.get("isajax", None)
    if isajax and entid[0] in ["e", "g", "p"] and entid[1:].isalnum():
        if entid[0] == "g":
            return HttpResponse(json.dumps(result), content_type="application/json")
        elif entid[0] == "p":
            result = get_person_child(0, int(entid[1:]), result, [])
            return HttpResponse(json.dumps(result), content_type="application/json")
        elif entid[0] == "e":
            entid = int(entid[1:])
            nodes_exist = ["e" + str(entid), ]
    else:
        entid = wldecode(entid, addcrc=True)
        if not entid:
            raise Http404
        el_posts = ELPost.objects.all()
        el_post = get_object_or_404(el_posts, entid=entid)
        result = {"id": str(uuid.uuid4()), "eid": "e" + str(entid), "name": str(el_post.ENTNAME), "tags": "0",
                  "size": "6", "children": []}
        nodes_exist = ["e" + str(entid), ]

    # 企业对外投资
    the_entinvs = ELInv.objects.filter(entid_inv=entid)
    if len(the_entinvs):
        for tinv in the_entinvs:
            if "e" + str(tinv.entobj_id) not in nodes_exist:
                new_child = {"id": str(uuid.uuid4()), "eid": "e" + str(tinv.entobj_id), "name": tinv.entid.ENTNAME,
                             "tags": "1", "size": "5",
                             "relation": "投资(%s%%)" % tinv.CONPROP}
                result["children"].append(new_child)
                nodes_exist.append("e" + str(tinv.entobj_id))

    # 法人对外投资和任职
    fr_personid, other_personids = ELPost.get_person_ids(entid)
    if fr_personid:
        the_person = ELManager.objects.filter(entobj=entid, personid=fr_personid).first()
        if the_person:
            edgetext = "法人"
            the_is = ELInv.objects.filter(entobj=entid, personid=fr_personid).first()
            if the_is:
                edgetext += ", 投资(%s%%)" % the_is.CONPROP
            if "p" + str(fr_personid) not in nodes_exist:
                new_child = {"id": str(uuid.uuid4()), "eid": "p" + str(fr_personid), "name": the_person.NAME,
                             "tags": "2", "size": "5",
                             "relation": edgetext, "children": []}
                nodes_exist.append("p" + str(fr_personid))
                new_child, nodes_exist = get_person_child(entid, fr_personid, new_child, nodes_exist)
                result["children"].append(new_child)

    # 股东高管对外投资和任职
    if len(other_personids):
        for o_personid in other_personids:
            the_person = ELPerson.objects.filter(personid=o_personid).first()
            the_ms = ELManager.objects.filter(entobj=entid, personid=o_personid).first()
            the_is = ELInv.objects.filter(entobj=entid, personid=o_personid).first()
            if the_person:
                edgetext = []
                if the_ms:
                    edgetext.append(the_ms.get_POSITION_display())
                if the_is:
                    edgetext.append("股东(%s%%)" % the_is.CONPROP)
                if "p" + str(o_personid) not in nodes_exist:
                    new_child = {"id": str(uuid.uuid4()), "eid": "p" + str(o_personid), "name": the_person.NAME,
                                 "tags": "2",
                                 "size": "5", "relation": ", ".join(edgetext), "children": []}
                    nodes_exist.append("p" + str(o_personid))
                    new_child, nodes_exist = get_person_child(entid, o_personid, new_child, nodes_exist)
                    result["children"].append(new_child)

    return HttpResponse(json.dumps(result), content_type="application/json")


# 企业图谱画图所需的企业基础信息，d3所需
@csrf_exempt
def get_tupu_basic(request, entid):
    context = dict()
    if entid[0] == "e" and entid[1:].isalnum():
        entid = int(entid[1:])
        el_posts = ELPost.objects.all()
        el_post = get_object_or_404(el_posts, entid=entid)
        context = {"el_post": el_post, "ntype": "e", "tax": {}}
        tax_year = ELFinanceTax.objects.filter(entid_id=entid, islatest=True).first()
        if tax_year:
            context["tax"] = {"revenue": tax_year.revenue,
                              "total_profit": tax_year.total_profit if tax_year.total_profit else "",
                              "assets_re": tax_year.assets_re if tax_year.assets_re else ""}
    elif entid[0] == "g" and entid[1:].isalnum():
        entid = int(entid[1:])
        el_posts = ELGeti.objects.all()
        el_post = get_object_or_404(el_posts, entid=entid)
        context = {"el_post": el_post, "ntype": "g", "tax": {}}
    elif entid[0] == "p" and entid[1:].isalnum():
        personid = int(entid[1:])
        el_post = ELPerson.objects.filter(personid=personid).first()
        if el_post:
            context = {"el_post": el_post, "ntype": "p", "tax": {}}
    return render(request, ["saas/related/d3_panel_detail.html"], context)


# 企业路径图的html模块
@never_cache
@login_required
def company_road(request):
    ntype1 = request.GET.get("ntype1", None)
    ntype2 = request.GET.get("ntype2", None)
    pk1 = request.GET.get("pk1", None)
    pk2 = request.GET.get("pk2", None)
    depth = request.GET.get("depth", 10)
    # 进行计费
    if customer_verify_fee(request, saas_pindao="20", saas_item="40",
                           tkey="%s-%s-%s-%s-%s" % (ntype1, ntype2, pk1, pk2, depth)):
        return HttpResponseRedirect(noauth_redirct_iframe)
    return render(request, "saas/related/road.html", {})


# 企业路径图数据生成主函数
@csrf_exempt
@never_cache
@login_required
def get_road_json(request):
    ntype1 = request.GET.get("ntype1", None)
    ntype2 = request.GET.get("ntype2", None)
    pk1 = request.GET.get("pk1", None)
    pk2 = request.GET.get("pk2", None)
    depth = request.GET.get("depth", 10)
    result = {"nodes": [], "edges": [], "table": []}
    if ntype1 in ["1", "2", "3", "4"] and ntype2 in ["1", "2", "3", "4"] and pk1 and pk2:
        if not neo4jhost_host:
            # 如果没有neo4j配置，则返回测试数据，用于本地开发环境
            result = related_road_json
        else:
            neoapi = Neo4jAPI()
            nodes_exist = []  # 记录已存在的节点
            filterdata = {'start_node': {}, 'end_node': {}, 'skip': 0, 'limit': 200, "depth": depth}
            if ntype1 in ["1", "2", ]:
                filterdata['start_node'] = {"name": "company", "companyId": pk1}
                result["nodes"].append(
                    {"name": road_name_from_id(pk1, "e"), "id": "e" + str(pk1), "type": "0", "imgtype": "startcom"})
                nodes_exist.append("e" + str(pk1))
            elif ntype1 in ["3", "4", ]:
                filterdata['start_node'] = {"name": "person", "personId": pk1}
                result["nodes"].append({"name": road_name_from_id(pk1, "p")[0], "id": "p" + str(pk1), "type": "1",
                                        "imgtype": road_name_from_id(pk1, "p")[1]})
                nodes_exist.append("p" + str(pk1))
            if ntype2 in ["1", "2", ]:
                filterdata['end_node'] = {"name": "company", "companyId": pk2}
                result["nodes"].append(
                    {"name": road_name_from_id(pk2, "e"), "id": "e" + str(pk2), "type": "0", "imgtype": "endcom"})
                nodes_exist.append("e" + str(pk2))
            elif ntype2 in ["3", "4", ]:
                filterdata['end_node'] = {"name": "person", "personId": pk2}
                result["nodes"].append({"name": road_name_from_id(pk2, "p")[0], "id": "p" + str(pk2), "type": "1",
                                        "imgtype": road_name_from_id(pk2, "p")[1]})
                nodes_exist.append("p" + str(pk2))
            neoresult = neoapi.find_path(filter_data=filterdata)
            # 记录最短路径
            minlength = 0
            for nr in neoresult:
                if len(nr) <= minlength or minlength == 0:
                    minlength = len(nr)
            for nr in neoresult:
                for ni in range(len(nr)):
                    if "company" in nr[ni] and "e" + nr[ni]["company"]["companyId"] not in nodes_exist:
                        result["nodes"].append({"name": road_name_from_id(nr[ni]["company"]["companyId"], "e"),
                                                "id": "e" + nr[ni]["company"]["companyId"], "type": "0",
                                                "imgtype": "com"})
                        nodes_exist.append("e" + nr[ni]["company"]["companyId"])
                    elif "person" in nr[ni] and "p" + nr[ni]["person"]["personId"] not in nodes_exist:
                        result["nodes"].append({"name": road_name_from_id(nr[ni]["person"]["personId"], "p")[0],
                                                "id": "p" + nr[ni]["person"]["personId"], "type": "1",
                                                "imgtype": road_name_from_id(nr[ni]["person"]["personId"], "p")[1]})
                        nodes_exist.append("p" + nr[ni]["person"]["personId"])
                    elif "geti" in nr[ni] and "g" + nr[ni]["geti"]["getiId"] not in nodes_exist:
                        result["nodes"].append({"name": road_name_from_id(nr[ni]["geti"]["getiId"], "g"),
                                                "id": "g" + nr[ni]["geti"]["getiId"], "type": "2", "imgtype": "geti"})
                        nodes_exist.append("g" + nr[ni]["geti"]["getiId"])
                    elif "entinv" in nr[ni] and 0 < ni < len(nr) - 1:
                        the_relation = gen_touzi_edgetext(nr[ni]["entinv"]["comprop"], nr[ni]["entinv"]["conam"],
                                                          direction=nr[ni]["direction"])
                        the_type = "best" if minlength == len(nr) else  "line"
                        result["edges"].append(
                            {"source": road_id_from_dict(nr[ni - 1]), "target": road_id_from_dict(nr[ni + 1]),
                             "relation": the_relation, "type": the_type})
                    elif "getiinv" in nr[ni] and 0 < ni < len(nr) - 1:
                        the_type = "best" if minlength == len(nr) else  "line"
                        result["edges"].append(
                            {"source": road_id_from_dict(nr[ni - 1]), "target": road_id_from_dict(nr[ni + 1]),
                             "relation": "个体户负责人", "type": the_type})
                    elif "perinv" in nr[ni] and 0 < ni < len(nr) - 1:
                        the_relation = gen_touzi_edgetext(nr[ni]["perinv"]["conprop"], nr[ni]["perinv"]["conam"],
                                                          direction=nr[ni]["direction"])
                        the_type = "best" if minlength == len(nr) else  "line"
                        result["edges"].append(
                            {"source": road_id_from_dict(nr[ni - 1]), "target": road_id_from_dict(nr[ni + 1]),
                             "relation": the_relation, "type": the_type})
                    elif "position" in nr[ni] and 0 < ni < len(nr) - 1:
                        the_relation = "%s" % dict(cb18_dict)[nr[ni]["position"]["position"]] if nr[ni]["position"][
                                                                                                     "position"] in dict(
                            cb18_dict).keys() else ""
                        the_type = "best" if minlength == len(nr) else  "line"
                        result["edges"].append(
                            {"source": road_id_from_dict(nr[ni - 1]), "target": road_id_from_dict(nr[ni + 1]),
                             "relation": the_relation, "type": the_type})
            result["edges"] = road_edge_distinct(result["edges"])

            # 渲染树表用的table数据
            table_data, rowid, roadid = OrderedDict(), 1, 1
            row_tmp = {"entid": "", "rowid": "", "roadid": "", "rowname": "", "nodename": "", "conam": "",
                       "conprop": "", "position": "",
                       "lerepsign": "", "regionid": "", "nicid": "", "regcap": "", "status": "", "esdate": "",
                       "sex": "", "parent": ""}
            for nr in neoresult:
                # 先查看路径是否存在
                road_now = []
                for ni in range(len(nr)):
                    if "company" in nr[ni]:
                        road_now.append("e" + nr[ni]["company"]["companyId"])
                    elif "geti" in nr[ni]:
                        road_now.append("g" + nr[ni]["geti"]["getiId"])
                    elif "person" in nr[ni]:
                        road_now.append("p" + nr[ni]["person"]["personId"])
                road_now = "-".join(road_now)
                if road_now not in table_data.keys():
                    # 路径不存在的情况，新增路径
                    row_road = copy.copy(row_tmp)
                    row_road["rowid"] = rowid
                    row_road["roadid"] = roadid
                    row_road["rowname"] = "路径-%s" % roadid
                    parent = rowid
                    rowid += 1
                    table_data[road_now] = [row_road]
                    for ni in range(len(nr)):
                        row_d = copy.copy(row_tmp)
                        row_d["rowid"] = rowid
                        row_d["roadid"] = roadid
                        row_d["parent"] = parent
                        if "company" in nr[ni]:
                            row_d["rowname"] = "企业"
                            row_d["entid"] = wlencode(nr[ni]["company"]["companyId"], addcrc=True)
                            row_d["nodename"] = road_name_from_id(nr[ni]["company"]["companyId"], "e")
                            row_d["regcap"] = kongtostr(nr[ni]["company"]["regcap"])
                            row_d["esdate"] = kongtostr(nr[ni]["company"]["esdate"])
                            the_entstatus, the_nic, the_region = "", "", ""
                            if nr[ni]["company"]["status"] in dict(ex02_dict).keys():
                                the_entstatus = dict(ex02_dict)[nr[ni]["company"]["status"]]
                            the_region = ELRegion.get_region(nr[ni]["company"]["regionid"], m="fulltitle")
                            tmp = ELNic.objects.filter(code=nr[ni]["company"]["nicid"].replace("!", "")).first()
                            if tmp:
                                the_nic = tmp.fulltitle
                            row_d["status"] = the_entstatus
                            row_d["regionid"] = the_region
                            row_d["nicid"] = the_nic
                        elif "geti" in nr[ni]:
                            row_d["rowname"] = "个体户"
                            row_d["nodename"] = road_name_from_id(nr[ni]["geti"]["getiId"], "g")
                            row_d["regcap"] = kongtostr(nr[ni]["geti"]["regcap"])
                            row_d["esdate"] = kongtostr(nr[ni]["geti"]["esdate"])
                            the_entstatus, the_nic, the_region = "", "", ""
                            if nr[ni]["geti"]["esdate"] in dict(ex02_dict).keys():
                                the_entstatus = dict(ex02_dict)[nr[ni]["geti"]["esdate"]]
                            the_region = ELRegion.get_region(nr[ni]["geti"]["regionid"], m="fulltitle")
                            tmp = ELNic.objects.filter(code=nr[ni]["geti"]["nicid"].replace("!", "")).first()
                            if tmp:
                                the_nic = tmp.fulltitle
                            row_d["status"] = the_entstatus
                            row_d["regionid"] = the_region
                            row_d["nicid"] = the_nic
                        elif "person" in nr[ni]:
                            row_d["rowname"] = "个人"
                            row_d["nodename"] = road_name_from_id(nr[ni]["person"]["personId"], "p")[0]
                            row_d["sex"] = "女" if road_name_from_id(nr[ni]["person"]["personId"], "p")[
                                                      1] == "woman" else "男"
                        elif "entinv" in nr[ni]:
                            row_d["rowname"] = "投资" if nr[ni]["direction"] == ">" else "股东"
                            row_d["conprop"] = kongtostr(nr[ni]["entinv"]["comprop"])
                            row_d["conam"] = kongtostr(nr[ni]["entinv"]["conam"])
                        elif "getiinv" in nr[ni]:
                            row_d["rowname"] = "负责人"
                            row_d["lerepsign"] = "是"
                        elif "perinv" in nr[ni]:
                            row_d["rowname"] = "投资"
                            row_d["conprop"] = kongtostr(nr[ni]["perinv"]["conprop"])
                            row_d["conam"] = kongtostr(nr[ni]["perinv"]["conam"])
                        elif "position" in nr[ni]:
                            row_d["rowname"] = "任职"
                            row_d["lerepsign"] = "是" if nr[ni]["position"]["lerepsign"] else "否"
                            row_d["position"] = "%s" % dict(cb18_dict)[nr[ni]["position"]["position"]] if \
                            nr[ni]["position"]["position"] in dict(
                                cb18_dict).keys() else ""
                        rowid += 1
                        table_data[road_now].append(row_d)
                    roadid += 1
                else:
                    # 路径已存在的情况
                    for ni in range(len(nr)):
                        if "perinv" in nr[ni] and table_data[road_now][ni + 1]["position"]:
                            table_data[road_now][ni + 1]["rowname"] = "投资并任职"
                            table_data[road_now][ni + 1]["conprop"] = kongtostr(nr[ni]["perinv"]["conprop"])
                            table_data[road_now][ni + 1]["conam"] = kongtostr(nr[ni]["perinv"]["conam"])
                        elif "position" in nr[ni]:
                            if table_data[road_now][ni + 1]["conam"] != "" or table_data[road_now][ni + 1][
                                "conprop"] != "":
                                table_data[road_now][ni + 1]["rowname"] = "投资并任职"
                            if not table_data[road_now][ni + 1]["position"]:
                                table_data[road_now][ni + 1]["lerepsign"] = "是" if nr[ni]["position"][
                                    "lerepsign"] else "否"
                                table_data[road_now][ni + 1]["position"] = "%s" % dict(cb18_dict)[
                                    nr[ni]["position"]["position"]] \
                                    if nr[ni]["position"]["position"] in dict(cb18_dict).keys() else ""
                            else:
                                if nr[ni]["position"]["position"] in dict(cb18_dict).keys() and dict(cb18_dict)[
                                    nr[ni]["position"]["position"]] not in \
                                        table_data[road_now][ni + 1]["position"]:
                                    table_data[road_now][ni + 1]["position"] += "，%s" % dict(cb18_dict)[
                                        nr[ni]["position"]["position"]]
                                if table_data[road_now][ni + 1]["lerepsign"] == "否" and nr[ni]["position"]["lerepsign"]:
                                    table_data[road_now][ni + 1]["lerepsign"] = "是"
            for k in table_data.keys():
                result["table"].extend(table_data[k])
    return HttpResponse(json.dumps(result), content_type="application/json")


@csrf_exempt
# 搜索时的节点验证
def related_node_check(request):
    ntype = request.GET.get("ntype", None)
    selectval = request.GET.get("selectVal", None)
    result = {"status": "error", "msg": ""}
    if ntype == "1" and selectval:
        the_post = ELPost.objects.filter(ENTNAME=selectval).first()
        if the_post:
            result["status"] = "success"
            result["msg"] = the_post.entid
    elif ntype == "2" and selectval:
        the_post = ELPost.objects.filter(Q(REGNO=selectval) | Q(UNISCID=selectval) | Q(NACAOID=selectval)).first()
        if the_post:
            result["status"] = "success"
            result["msg"] = the_post.entid
    elif ntype == "3" and selectval:
        the_person = ELPerson.objects.filter(CERNO=selectval).first()
        if the_person:
            result["status"] = "success"
            result["msg"] = the_person.personid
    elif ntype == "4" and selectval and "￥￥￥" in selectval:
        [val1, val2] = selectval.split("￥￥￥")
        the_post = ELPost.objects.filter(ENTNAME=val1).first()
        if the_post:
            the_person = ELManager.objects.filter(entobj=the_post.entid, NAME=val2).first()
            if the_person and the_person.personid_id:
                result["status"] = "success"
                result["msg"] = the_person.personid_id
            else:
                the_person = ELInv.objects.filter(entobj=the_post.entid, INV=val2).first()
                if the_person and the_person.personid:
                    result["status"] = "success"
                    result["msg"] = the_person.personid_id
    return HttpResponse(json.dumps(result), content_type="application/json")
